import { PropEditor } from "maishu-jueying";
import { Props as ComponentProps } from "./component";
import React = require("react");
import { createService } from "components/common/base-component";
import { ShoppingService } from "mobile/services/shoppingService";
import { ImageService } from "maishu-services-sdk";
import { renderImage } from "maishu-ui-toolkit";
import { ProductSelectDialog } from "controls/product-select-dialog";

interface ProductSourceEditorState {
    value: ComponentProps["productIds"],
    products?: Product[]
}
export class ProductSourceEditor extends PropEditor<ProductSourceEditorState, ComponentProps["productIds"]> {
    shoppingService: ShoppingService;
    productThumbers: HTMLElement;
    imageService: ImageService;

    constructor(props) {
        super(props);
        this.shoppingService = createService(ShoppingService);
        this.imageService = createService(ImageService);
    }
    setProductDelete(e: HTMLButtonElement, productId: string) {
        if (!e || e.onclick)
            return;

        e.onclick = () => {
            let value = this.state.value.filter(o => o != productId);
            this.setState({ value });
        }
    }
    setProductAdd(e: HTMLElement) {
        if (!e || e.onclick)
            return;

        e.onclick = () => {
            ProductSelectDialog.show((products) => this.productSelected(products));
        }
    }
    productSelected(products: Product[]): Promise<any> {
        let productIds = this.state.value || [];

        // 排除已存在的 product id
        let newProducts = products.map(o => o.Id).filter(o => productIds.indexOf(o) < 0)

        productIds.push(...newProducts);

        // this.state.productIds = productIds;
        this.setState({ value: productIds });
        return Promise.resolve();
    }
    render() {
        let { products } = this.state;
        products = products || [];
        return <div className="product-list-editor">
            <ul className="selected-products"
                ref={(e: HTMLElement) => this.productThumbers = e || this.productThumbers}>
                {products.map(o =>
                    <li key={o.Id} product-id={o.Id} title="拖动图标可以对商品进行排序">
                        <img src={this.imageService.imageSource(o.ImagePath, 100)}
                            ref={(e: HTMLImageElement) => e ? renderImage(e) : null} />
                        <div className="delete">
                            <button type="button" className="btn-link"
                                ref={(e: HTMLButtonElement) => this.setProductDelete(e, o.Id)}>
                                删除
                    </button>
                        </div>
                    </li>
                )}
                <li className="product-add">
                    <i className="icon-plus icon-4x" ref={(e: HTMLElement) => this.setProductAdd(e)} />
                </li>
            </ul>
        </div>
    }
}

